package com.plug.controller;

import com.plug.common.consts.Code;
import com.plug.common.jdbc.DBConnectionManager;
import com.plug.common.jdbc.DBConnectionPool;
import com.plug.common.model.ExceptionResult;
import com.plug.common.model.JsonResult;
import com.plug.common.spring.utils.ApplicationContextHelper;
import com.plug.controller.util.AbstractController;
import com.plug.entity.PlugContrast;
import com.plug.entity.PlugDatasource;
import com.plug.service.IPlugDatasourceService;
import com.plug.service.PlugOperationRecordServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2017/1/16.
 */
@Controller
@RequestMapping("/selectTabController")
public class SelectTabController extends PlugOperationRecordServiceImpl {
    @Autowired
    private IPlugDatasourceService plugDatasourceService;

    private Logger logger = LoggerFactory.getLogger(getClass());
    private DBConnectionManager dbConnectionManager = DBConnectionManager.getInstance();

    /**
     * 查看数据库表格数据
     *
     *
     * @param page
     * @param limit
     * @param srcId
     * @param tabName
     * @param uid
     * @param firstId
     * @param endId
     * @return
     */
    @RequestMapping(value = "/selectTab")
    @ResponseBody
    public ResponseEntity<Object> selectTab(@RequestParam("page") Integer page,
                                            @RequestParam("limit") Integer limit,
                                            @RequestParam("srcId") Integer srcId,
                                            @RequestParam("tabName") String tabName,
                                            @RequestParam("uid") String uid,
                                            @RequestParam("firstId") Integer firstId,
                                            @RequestParam("endId") Integer endId) {

         List<Object> result = new ArrayList<>();
        result = selectTabData( page, limit, srcId, tabName, uid, firstId, endId);
        try {
            if(result.size()>0) {
                JsonResult jsonResult = new JsonResult();//源数据集
                jsonResult.setCode(Code.SUCCESS);
                jsonResult.putData("resultLie", result.get(0));//表格列名
                jsonResult.putData("resultData", result.get(1));//表格数据
                jsonResult.putData("total", result.get(2)); //数据总条数
                return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
            }else{
                return new ResponseEntity<Object>(null, HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity<Object>(new ExceptionResult(((Exception)result.get(0))), HttpStatus.OK);
        }

//        long src = srcId;
//        Connection srcConn = null;
//        PlugDatasource srcY = null;
//        try {
//            srcY = plugDatasourceService.findByID(src);
//            srcConn = dbConnectionManager.getConnection(DBConnectionPool.createJDBCInfoBean(srcY));
//        } catch (Exception e) {
//            return new ResponseEntity<Object>(new ExceptionResult(e),HttpStatus.OK);//返回异常数据
//        }
//        List<Map<String, Object>> resultData = new ArrayList<>();
//        List<Map<String, Object>> resultLie = new ArrayList<>();
//        //如果page与limit==0,赋值=1，使下面sql语句始终能够有值
//        if (page == 0 || page == null || limit == 0 || limit == null) {
//            page = 1;
//            limit = 1;
//        }
//        String sql = null;//查询记录
//        String sql2 = null;//判断查询记录的总条数
//        logger.debug("------------firstId---{}-------endId--{}----", firstId,endId);
//        if(firstId == null ){
//            firstId = 0;
//        }
//            //判断初始位置和起始位置的值，调用相应的sql;
//        if((firstId == 0 && endId ==null)){
//            sql = "select * from  " + tabName + " limit " + (page - 1) * limit + "," + limit + "";
//            sql2 = "select count(*) from  " + tabName + "";
//            logger.debug("---------------{}-------------", sql);
//        }
//        if(firstId == 0 && endId !=null){
//            sql = "select * from  " + tabName + " where "+uid+" < "+endId+"  limit " + (page - 1) * limit + "," + limit + "";
//            sql2 = "select count(*) from  " + tabName + " where "+uid+" < "+endId+"";
//            logger.debug("---------------{}-------------", sql);
//        }
//        if((firstId != 0 && endId ==null)){
//            sql = "select * from  " + tabName + " where "+uid+" > "+firstId+"  limit " + (page - 1) * limit + "," + limit + "";
//            sql2 = "select count(*) from  " + tabName + " where "+uid+" > "+firstId+"";
//            logger.debug("---------------{}-------------", sql);
//        }
//        if(firstId != 0 && endId !=null){
//            sql = "select * from  " + tabName + " where "+uid+" < "+endId+" and "+uid+" > "+firstId+" limit " + (page - 1) * limit + "," + limit + "";
//            sql2 = "select count(*) from  " + tabName + " where "+uid+" < "+endId+" and "+uid+" > "+firstId+"";
//            logger.debug("---------------{}-------------", sql);
//        }
//        int total = 0;
//        try {
//            ResultSet rs = null;
//            PreparedStatement ps = null;
//           // String sql = "select * from  " + tab + " limit 0," + pagesize + "";
//            ps = srcConn.prepareStatement(sql);
//            rs = ps.executeQuery();
//            //获取结果集元数据
//            ResultSetMetaData rsmd = rs.getMetaData();
//            //总列数
//            int size = rsmd.getColumnCount();
//            Map<String, Object> map = new HashMap<>();
//            for (int i = 1; i <= size; i++) {
//                map = new HashMap<>();
//                map.put("field", rsmd.getColumnName(i));
//                map.put("title", rsmd.getColumnName(i));
//                map.put("align", "center");
//                map.put("editor", "text");
//                resultLie.add(map);
//            }
//            //查询数据库表格里面的值，返回到前端表格
//            int num = 3;
//            while (rs.next()) {
//                map = new HashMap<>();
//                for (int i = 1; i <= size; i++) {
//                    map.put(rsmd.getColumnName(i), rs.getObject(i));
//                }
//                resultData.add(map);
//            }
//            //查询总条数total
//            //String sql2 = "select count(*) from  " + tabName + "";
//            ps = srcConn.prepareStatement(sql2);
//            rs = ps.executeQuery();
//            while (rs.next()) {
//                total = rs.getInt(1);
//            }
//            ps.close(); rs.close(); rs = null;ps = null;
//            JsonResult jsonResult = new JsonResult();//源数据集
//            jsonResult.setCode(Code.SUCCESS);
//            jsonResult.putData("resultData", resultData);
//            jsonResult.putData("resultLie", resultLie);
//            jsonResult.putData("total", total);
//            logger.debug("---------------total{}----------------", total); //记录器
//            return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
//        } catch (SQLException e) {
//            return new ResponseEntity<Object>(new ExceptionResult(e),HttpStatus.OK);//返回异常数据
//        } finally {
//            if (srcConn != null) {
//                dbConnectionManager.freeConnection(srcY.getDsName(), srcConn);
//            }
//        }
//        } else {
//            int total = 0;
//            try {
//                String tab = "srctest";
//                ResultSet rs = null;
//                PreparedStatement ps = null;
//                String sql = "select * from  " + tab + " limit " + (page - 1) * limit + "," + limit + "";
//               //logger.debug("---------------{}---{}-------------", (page - 1) * limit, limit);
//                ps = srcConn.prepareStatement(sql);
//                rs = ps.executeQuery();
//                //获取结果集元数据
//                ResultSetMetaData rsmd = rs.getMetaData();
//                //总列数
//                int size = rsmd.getColumnCount();
//                Map<String, Object> map = new HashMap<>();
//                for (int i = 1; i <= size; i++) {
//                    map = new HashMap<>();
//                    map.put("field", rsmd.getColumnName(i));
//                    map.put("title", rsmd.getColumnName(i));
//                    map.put("align", "center");
//                    map.put("editor", "text");
//                    resultLie.add(map);
//                }
//                //查询数据库表格里面的值，返回到前端表格
//                int num = 3;
//                while (rs.next()) {
//                    map = new HashMap<>();
//                    for (int i = 1; i <= size; i++) {
//                        map.put(rsmd.getColumnName(i), rs.getObject(i));
//                    }
//                    resultData.add(map);
//                }
//                ps.close();
//                rs.close();
//                rs = null;
//                ps = null;
//                String sql2 = "select count(*) from  " + tab + "";
//                ps = srcConn.prepareStatement(sql2);
//                rs = ps.executeQuery();
//                while (rs.next()) {
//                    total = rs.getInt(1);
//                }
//                ps.close();
//                rs.close();
//                rs = null;
//                ps = null;
//            } catch (SQLException e) {
//                e.printStackTrace();
//            } finally {
//                if (srcConn != null) {
//                    dbConnectionManager.freeConnection(srcY.getDsName(), srcConn);
//                }
//            }
//            JsonResult jsonResult = new JsonResult();//源数据集
//            jsonResult.putData("resultData", resultData);
//            jsonResult.putData("resultLie", resultLie);
//            jsonResult.putData("total", total);
//            return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
//      }

    }

}